import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { arieaEchoRender, arieaFormSubmit, getKeyRouter, getLoadMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { Form, Spin, message } from 'antd';
import React, { Ref, useContext, useEffect, useRef } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { ILoadMapTypeAll } from '@/common';
import { ISupplierActionEnum, SupplierLocaldataContext } from '../common';
import moment from 'moment';
import { addContactsService, editContactsService, getContacterByIdService } from '../services';
import { ContactsUpdateModalForm } from './ContactsUpdateModalForm';

export const ContactsUpdateModal: React.FC<SupplierManageAPI.IContactsUpdateModal> = ({ onClose, currentContactsInfo }) => {
  /** 弹框Ref */
  const contactsUpdateRef: Ref<IOneModalRef> = useRef(null);

  /** 表单 form */
  const [updateForm] = Form.useForm();

  /** 获取上下文 */
  const { locationID, supplierDispath, contactsSwitchList, reloadDetailInfo } = useContext(SupplierLocaldataContext);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.NATION_TYPE}`,
    `${getTenantID()}${ILoadMapTypeAll.POLITICAL_OUTLOOK}`,
    `${getTenantID()}${ILoadMapTypeAll.EDUCATION_LEVEL}`,
    `${getTenantID()}${ILoadMapTypeAll.EXPERTS_CARD_TYPE}`, //证件类型
  ]);

  /**
   * 联系人详情
   * @param res
   */
  const getContactsByIdCallback = (res: any) => {
    if (res && res?.msgFlag) {
      updateForm?.setFieldsValue({
        ...res?.obj,
        contaNode: arieaEchoRender(res?.obj),
        birthday: res?.obj?.birthday ? moment(res?.obj?.birthday) : null,
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入详情接口 */
  const { getContacterByIdLoading, getContacterByIdRun, getContacterByIdInfo } = getContacterByIdService(getContactsByIdCallback);

  /**初始化 */
  useEffect(() => {
    if (currentContactsInfo && currentContactsInfo?.key) {
      updateForm?.setFieldsValue({
        ...currentContactsInfo,
        contaNode: arieaEchoRender(currentContactsInfo),
        birthday: currentContactsInfo?.birthday ? moment(currentContactsInfo?.birthday) : null,
      });
    } else if (currentContactsInfo && currentContactsInfo?.id) {
      getContacterByIdRun({ id: currentContactsInfo?.id });
      // updateForm?.setFieldsValue({  //模拟数据-王志龙
      //   ...currentContactsInfo,
      //   contaNode: arieaEchoRender(currentContactsInfo),
      //   birthday: currentContactsInfo?.birthday ? moment(currentContactsInfo?.birthday) : null,
      // });
    }
  }, [currentContactsInfo]);

  /**
   * 添加编辑联系人接口回调
   * @param res 接口返回数据
   */
  const contactsUpdateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadDetailInfo();
      onCloseModalCommon(contactsUpdateRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入添加接口 */
  const { addContactsLoading, addContactsRun } = addContactsService(contactsUpdateCallback);

  /** 引入编辑接口 */
  const { editContactsLoading, editContactsRun } = editContactsService(contactsUpdateCallback);

  /** 保存按钮 */
  const onSave = () => {
    updateForm?.validateFields()?.then((values: any) => {
      const areaCodeList: Record<string, any> = arieaFormSubmit(values?.contaNode);
      let updatePaylod: any = {
        key: `contasts-${getKeyRouter()}`,
        ...currentContactsInfo,
        ...values,
        ...areaCodeList,
        birthday: values?.birthday ? values?.birthday.format('YYYY-MM-DD 00:00:00') : null,
        cardTypeName: loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.EXPERTS_CARD_TYPE}`]?.find(
          (item: any) => item?.id == values?.cardType,
        )?.name,
        educateLevelName: loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.EDUCATION_LEVEL}`]?.find(
          (item: any) => item?.id == values?.educateLevel,
        )?.name,
        nationTypeName: loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.NATION_TYPE}`]?.find(
          (item: any) => item?.id == values?.nationType,
        )?.name,
        politicalTypeName: loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.POLITICAL_OUTLOOK}`]?.find(
          (item: any) => item?.id == values?.politicalType,
        )?.name,
      };
      delete updatePaylod['contaNode'];
      if (locationID) {
        /** 编辑供应商逻辑 */
        if (getContacterByIdInfo && getContacterByIdInfo?.id) {
          let editPayload: Record<string, any> = {
            ...values,
            ...areaCodeList,
            birthday: values?.birthday ? values?.birthday.format('YYYY-MM-DD 00:00:00') : null,
            id: getContacterByIdInfo?.id,
            versionNum: getContacterByIdInfo?.versionNum,
            supplierID: locationID,
          };
          delete editPayload['contaNode'];
          editContactsRun(editPayload);
        } else {
          updatePaylod['supplierID'] = locationID;
          addContactsRun(updatePaylod);
        }
      } else {
        let newContacList: Record<string, any>[] = [...contactsSwitchList];
        if (currentContactsInfo && currentContactsInfo?.key) {
          const contactIndex: number = newContacList?.findIndex((item: any) => item?.key == currentContactsInfo?.key);
          newContacList[contactIndex] = updatePaylod;
        } else {
          newContacList?.push(updatePaylod);
        }
        supplierDispath({
          type: ISupplierActionEnum.CHECKLIST_CONTACTS,
          payload: newContacList,
        });

        onCloseModalCommon(contactsUpdateRef);
      }
    });
  };

  return (
    <OneModal
      open={true}
      ref={contactsUpdateRef}
      title={currentContactsInfo?.fullName ? '编辑相关联系人' : '添加相关联系人'}
      width={document.body.clientWidth * 0.5}
      onCancel={onClose}
      bodyStyle={{
        padding: '5px 10px',
      }}
      centered
      onOk={onSave}
      confirmLoading={addContactsLoading || editContactsLoading || getContacterByIdLoading}
    >
      <Spin spinning={addContactsLoading || editContactsLoading || getContacterByIdLoading}>
        <div className={pageStyles['fromView-styles']}>
          <Form form={updateForm}>
            <ContactsUpdateModalForm nameForm={updateForm} loadMapInfo={loadMapInfo} mapLoading={mapLoading} />
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
